package com.na.tools;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {
	
	public static class HttpRequest {
		public String url;
		public String method;
		public String[] requestHeaders;
		public String[] requestParams;
	}
	
	public static byte[] request(HttpRequest request) throws IOException {
		return httpRequest(request.method, request.url, request.requestParams, request.requestHeaders);
	}

	public static byte[] post(String url, String... params) throws IOException {
		return httpRequest("POST", url, params, null);
	}
	
	public static byte[] get(String url, String... params) throws IOException {
		return httpRequest("GET", url, params, null);
	}
	
	private static byte[] httpRequest(String method, String url, String[] params, String[] headers) throws IOException {
		if (!"POST".equals(method) && !"GET".equals(method)) {
			throw new IllegalArgumentException("not supported method: " + method);
		}
		HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
		conn.setRequestMethod(method);
		conn.setDoOutput(true);
//		conn.setDoInput(true);
		if (headers != null && headers.length > 0) {
			for (int i = 0; i < headers.length; i += 2) {
				conn.setRequestProperty(headers[i], headers[i + 1]);
			}
		}
		StringBuilder bufRequestUrl = new StringBuilder();
		if (params != null && params.length > 0) {
			for (int i = 0; i < params.length; i += 2) {
				if (i != 0) {
					bufRequestUrl.append('&');
				}
				bufRequestUrl.append(params[i]).append('=').append(params[i + 1]);
			}
			OutputStream out = conn.getOutputStream();
			out.write(bufRequestUrl.toString().getBytes("UTF-8"));
			out.close();
		}
		bufRequestUrl.insert(0, url + '?');
		System.out.println(bufRequestUrl.toString());
		InputStream in = conn.getInputStream();
		ByteArrayOutputStream buf = new ByteArrayOutputStream(512);
		byte[] buffer = new byte[512];
		int len;
		buf.reset();
		while ((len = in.read(buffer)) != -1) {
			buf.write(buffer, 0, len);
		}
		in.close();
		conn.disconnect();
		return buf.toByteArray();
	}
	
}
